package team.bluepen.supermarket.kafka;

import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.ProducerConfig;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.apache.kafka.common.serialization.Serializer;
import org.apache.kafka.common.serialization.StringSerializer;

import java.io.Closeable;
import java.util.Properties;

/**
 * @author RollW
 */
public class KafkaPusher<T> implements Closeable {
    private static final Serializer<String> STRING_SERIALIZER = new StringSerializer();

    private final String topic;
    private final KafkaProducer<String, String> producer;
    private final KafkaSerializer<T> serializer;

    public KafkaPusher(String topic, String servers,
                       KafkaSerializer<T> serializer) {
        Properties properties = new Properties();
        properties.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, servers);
        producer = new KafkaProducer<>(properties, STRING_SERIALIZER, STRING_SERIALIZER);
        this.topic = topic;
        this.serializer = serializer;
    }

    public void push(T data) {
        final String serialized = serializer.serialize(data);
        ProducerRecord<String, String> record = new ProducerRecord<>(
                topic,
                serialized);
        producer.send(record);
        producer.flush();
    }

    public void push(String key, T data) {
        final String serialized = serializer.serialize(data);
        ProducerRecord<String, String> record = new ProducerRecord<>(
                topic, key,
                serialized);
        producer.send(record);
        producer.flush();
    }

    public String getTopic() {
        return topic;
    }

    @Override
    public void close() {
        stop();
    }

    public void stop() {
        producer.close();
    }
}
